<?php
namespace Qgs\Controller;

use Qgs\Controller\BaseController;
use Common\Model\BillsExportModel;
use Think\Model;

class QgsBillsController extends BaseController
{

    /**
     * 对账单首页列表
     */
    public function index()
    {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 20);
        $this->assign('page', $p);
        $this->assign('num', $num);

        $order_field = I('param.order_field', 'id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);
        $locals = M('webpos_local_store')->field('local_id,local_name')->select();
        $this->assign('locals', $locals);
        $start_time = I('get.start_time', '', 'htmlspecialchars');//开始时间
        $end_time = I('get.end_time', '', 'htmlspecialchars');//结束时间
        $local_id = I('get.local_id', '', 'intval');//门店id
        $state = I('get.state');//结算状态

        $search_field = I('param.search_field');
        $search = trim(I('param.search'));
        $where[0] = ['is_terrace'=>2];
        if ($local_id) {
            $where[] = ['local_id' => $local_id];
        }
        if (isset($start_time)) {
            $format_start_time = strtotime($start_time);
            if ($format_start_time > 0) {

                $where[] = ['start_time' => ['egt', $format_start_time]];
            }
        }
        if (isset($end_time)) {
            $format_end_time = strtotime($end_time);
            if ($format_end_time > 0) {

                $where[] = ['end_time' => ['lt', $format_end_time]];
            }
        }
        if (isset($state) && $state !== '') {
            $where[] = ['state' => $state];
        }
        if ($search && $search_field) {
            $where[] = $search_field . " like '%" . $search . "%'";
            $this->assign('search', $search);
            $this->assign('search_field', $search_field);
        }
        $count = M('b2c_bills_account')
            ->where($where)
            ->count();
        $Page = new \Think\Page($count, $num);
        $show = $Page->show();
        $data = M('b2c_bills_account')
            ->page($p, $num)
            ->where($where)
            ->order($order)
            ->select();
        //echo M()->_sql();
        $this->assign('list', $data);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 对账单查询和渲染页面
     */
    public function add()
    {

        //获取所有的门店列表 local_name local_id
        $locals = M('webpos_local_store')->field('local_id,local_name')->select();
        $this->assign('locals', $locals);

        $local_id = I('get.local_id', 0, 'intval');
        $start_time = I('get.start_time', '', 'htmlspecialchars');
        if (isset($start_time)) {
            $format_start_time = strtotime($start_time);
            if ($format_start_time > 0) {

                $start_time = $format_start_time;
            } else {
                $start_time = 0;
            }
        }
        $end_time = I('get.end_time', '', 'htmlspecialchars');
        if (isset($end_time)) {
            $format_end_time = strtotime($end_time);
            if ($format_end_time > 0) {

                $end_time = $format_end_time + 86400;
            } else {
                $end_time = 86400;
            }
        }
        $list = [];
        if ($local_id && $start_time && $end_time) {
            //查询出支付方式
            $payments = M('b2c_payment')->getField('name', true);
            $where = [
                'a.local_id' => 11,
                'a.relation_local_id' => $local_id,
                'a.js_type' => 0,
                'a.status' => 'finish',
                'a.createtime' => [['egt', $start_time], ['lt', $end_time]],
            ];

            //获取  店铺 时间段 的收款订单
            $field = 'a.ship_name,a.order_id,a.cost_freight,a.total_amount,a.payed,a.last_modified,a.paymethod_id,a.cost_item,b.item_id,b.name,b.price,b.g_price,b.nums,b.qgs_fee,b.qgs_rate,c.nickname';
            $list['order'] = M('b2c_orders')
                ->alias('a')
                ->join(C('DB_PREFIX') . 'b2c_order_items b on a.order_id=b.order_id', 'LEFT')
                ->join(C('DB_PREFIX') . 'b2c_members c on a.member_id=c.member_id', 'LEFT')
                ->field($field)
                ->where($where)
                ->select();
            //echo M()->_sql();die;
            //dump($list['order']);
            //todo 银行手续费暂时不处理
            if ($list['order']) {
                $order = [];
                $tmp = [];
                $orderIds = [];
                foreach ($list['order'] as $item) {
                    //查询是否退款
                    $refundSql = "SELECT rg.*,rm.price FROM `sdb_b2c_refund_money_goods` rg INNER JOIN `sdb_b2c_refund_money` rm ON rg.refund_money_id = rm.id WHERE rm.`status` = '5' and rg.order_id = {$item['order_id']}";
                    $refundData = M()->query($refundSql);
                    //获取order_id
                    if(!in_array($item['order_id'],$orderIds)){
                        array_push($orderIds,$item['order_id']);
                    }
                    $order[$item['order_id']]['order_id'] = $item['order_id'];//订单id
                    $order[$item['order_id']]['total_amount'] = $item['total_amount'];//实际支付价格
                    $order[$item['order_id']]['cost_freight'] = $item['cost_freight'];//物流费用
                    $order[$item['order_id']]['cost_item'] = $item['cost_item'];//订单价格
                    $order[$item['order_id']]['createtime'] = $item['last_modified'];//完成日期
                    $order[$item['order_id']]['paymethod_id'] = $item['paymethod_id'];//支付方式
                    $order[$item['order_id']]['nickname'] = $item['nickname'];//会员昵称
                    $order[$item['order_id']]['ship_name'] = $item['ship_name'];//收货人
                    if ($item['paymethod_id']) {
                        $order[$item['order_id']]['paymethod_name'] = $payments[$item['paymethod_id'] - 1];//支付方式
                    } else {
                        $order[$item['order_id']]['paymethod_name'] = '';
                    }
                    $order[$item['order_id']]['list'] = [];
                    //dump($item['qgs_rate']);
                    $ii = [
                        'name' => $item['name'],//货品名称
                        'nums' => $item['nums'],//数量
                        'qgs_rate' => $item['qgs_rate'],
                        'qgs_fee' => $item['qgs_fee'],
                        'youhui' => bcsub($item['g_price'], $item['price'], 2),   //g_price原价 price购入价
                    ];

                    foreach($refundData as $k1 => $v1){
                        if($item['item_id'] == $v1['item_id']){
                            if($item['nums'] == $v1['num']){
                                $ii = '';
                            }else{
                                $ii['nums'] = $item['nums'] - $v1['num'];
                                //真实佣金 = 下单佣金减去退款的佣金
                                $ii['qgs_fee'] = round(bcsub($item['qgs_fee'] , ($v1['price'] * $item['qgs_fee']/100),3),2);
                            }
                        }
                    }
                    if($ii){
                        $tmp[$item['order_id']][] = $ii;
                        $order[$item['order_id']]['list'] = $tmp[$item['order_id']];
                        $order[$item['order_id']]['yongjin'] = array_sum(array_column($tmp[$item['order_id']], 'qgs_fee'));
                    }
                    $order[$item['order_id']]['geshu'] = count($order[$item['order_id']]['list']);
                }
                sort($order);
                //dump($orderIds);
                //订单共计
                $statistics = [];
                $statistics['order_num'] = count($order);
                $statistics['total_money'] = '0.00';
                $statistics['commission'] = '0.00';
                foreach ($order as $item) {
                    $statistics['total_money'] = bcadd($statistics['total_money'], $item['total_amount'], 2);    //订单实支付总金额
                    if ($item['list']) {
                        foreach ($item['list'] as $value) {
                            //抽佣总额
                            $statistics['commission'] = bcadd($statistics['commission'], $value['qgs_fee'], 2);
                        }
                    }
                }
                //dump($order);
                $this->assign(['order' => $order, 'statistics' => $statistics]);
            }

        }
        $this->display('add');
    }

    public function rebuildOrders($orderids, $bank, $other)
    {

        $where = [
            //'a.bill_type' => 'payments',
            'a.order_id' => ['in', $orderids],
        ];
        $field = 'a.ship_name,a.order_id,a.cost_freight,a.total_amount,a.payed,a.last_modified,a.paymethod_id,a.cost_item,b.name,b.price,b.g_price,b.nums,b.qgs_fee,b.qgs_rate,b.item_id,c.nickname';
        $orderlist = M('b2c_orders')
            ->alias('a')
            ->join(C('DB_PREFIX') . 'b2c_order_items b on a.order_id=b.order_id', 'LEFT')
            ->join(C('DB_PREFIX') . 'b2c_members c on a.member_id=c.member_id', 'LEFT')
            ->field($field)
            ->where($where)
            ->select();
        //echo M()->_sql();
        //var_dump($where);return;

        $orderZ['nums'] = count($orderids);
        $orderZ['bank'] = $bank;
        $orderZ['other'] = $other;
        $orderZ['total_pay'] = $orderZ['total_off'] = $orderZ['total_yongjin'] = 0;
        if ($orderlist) {

            $tmp = $new = [];
            foreach ($orderlist as $item) {
                if (!in_array($item['order_id'], $tmp)) {
                    $orderZ['total_pay'] = bcadd($orderZ['total_pay'], $item['total_amount'], 2);
                }
                array_push($tmp, $item['order_id']);

                $orderZ['total_off'] = bcadd($orderZ['total_off'], bcsub($item['g_price'], $item['price'], 2), 2);
                $orderZ['total_yongjin'] = bcadd($orderZ['total_yongjin'], $item['qgs_fee'], 2);
            }
        }
        $orderZ['origin_price'] = $orderZ['total_pay']; //原始价格
        $orderZ['total_pay'] = bcsub($orderZ['total_pay'], $orderZ['total_yongjin'], 2); //除去佣金的价格
//        var_dump($orderZ['origin_price'],$orderZ['total_off'],$orderZ['bank'],$orderZ['other'],$orderZ['total_yongjin']);exit;
//        $orderZ['final_price'] = bcsub($orderZ['origin_price'], bcadd($orderZ['total_off'], bcadd($orderZ['bank'], bcadd($orderZ['other'], $orderZ['total_yongjin'],2), 2),2),2); //除去佣金 银行 优惠 其他 之后的最终订单价格
        //公式 ： 应结算金额 = 订单支付总额 - 抽佣总额 - 银行手续费
        $orderZ['final_price'] = bcsub($orderZ['origin_price'], bcadd($orderZ['bank'], bcadd($orderZ['other'], $orderZ['total_yongjin'], 2), 2), 2); //除去佣金 银行 优惠 其他 之后的最终订单价格
        //var_dump($orderZ);return;
        return ['orderlist' => $orderlist, 'orderZ' => $orderZ];
    }

    public function rebuildRefund($refundids, $other2)
    {
        //订单数量 订单退款总金额  返还抽佣总额  其他 应退款总金额

        $refundZ['nums'] = count($refundids);
        $refundZ['other'] = $other2;
        $where = [
            'a.bill_type' => 'refunds',
            'a.order_id' => ['in', $refundids],
        ];
        $refundlist = M('b2c_bills')
            ->alias('a')
            ->join(C('DB_PREFIX') . 'b2c_refund_money_goods b on a.refund_id=b.refund_money_id', 'LEFT')
            ->join(C('DB_PREFIX') . 'b2c_order_items c on b.item_id=c.item_id', 'LEFT')
            ->field('a.order_id,a.store_work_logs,a.price_detail,a.finance_name,a.finance_user,a.finance_confirm_t,a.store_work_logs,c.name,c.price,c.g_price,c.nums,c.qgs_fee,c.qgs_rate')
            ->where($where)
            ->select();
        if ($refundlist) {
            $tmp = $new = [];
            foreach ($refundlist as $item) {
                if (!in_array($item['order_id'], $tmp)) {
                    $refundZ['total_pay'] = bcadd($refundZ['total_pay'], $item['price_detail'], 2);

                }
                array_push($tmp, $item['order_id']);
                $refundZ['total_yongjin'] = bcadd($refundZ['total_yongjin'], $item['qgs_fee'], 2);
            }
            $refundZ['origin_price'] = $refundZ['total_pay'];
            //echo $refundZ['total_yongjin'].'----'.$refundZ['total_pay'].'----'.$refundZ['other'];exit;
            // 公式 ： 应退款总金额 = 订单退款总金额 - 退款返还的抽佣金额 - 其他
            $refundZ['final_price'] = bcsub(bcsub($refundZ['total_pay'], $refundZ['total_yongjin'], 2), $refundZ['other'], 2);
            // echo $refundZ['final_price'];exit;
            $refundZ['total_pay'] = bcsub($refundZ['total_pay'], $refundZ['total_yongjin'], 2);
        }
//        var_dump(['refundlist'=>$refundlist, 'refundZ'=>$refundZ]);return;
        return ['refundlist' => $refundlist, 'refundZ' => $refundZ];
    }

    /**
     * 生成对账单(插入数据库)
     */
    public function save()
    {
        $orderids = I('post.order', []);
        $bank = I('post.bank');
        $other = I('post.other');
        $refundids = I('post.refund', []);
        $other2 = I('post.other2');
        $handle_name = I('post.handle_name');
        $handle_tips = I('post.handle_tips', '');
        $local_id = I('post.local_id', 1);
        $local_name = M('webpos_local_store')->where(['local_id' => $local_id])->getField('local_name');
        $start_time = strtotime(I('post.start_time', 0));

        $end_time = strtotime(I('post.end_time', 0));
        //重建order总结数据
        $orderres = $this->rebuildOrders($orderids, $bank, $other);
        //dump($orderres);
        $orderlist = $orderres['orderlist'];
        $orderZ = $orderres['orderZ'];
        //重建refund总结数据
        $refundres = $this->rebuildRefund($refundids, $other2);
        $refundlist = $refundres['refundlist'];
        $refundZ = $refundres['refundZ'];
        //开启事务 准备插入
        //1.先新增条目sdb_b2c_bills_account
        $account_id = $this->buildNubmer();

        //var_dump($orderZ,$refundZ,$account);return;
        $db = M();
        $db->startTrans();

        //在进行订单表的数据的插入
        //dump($orderlist);die;
        if ($orderlist) {
            //组装数据入sdb_b2c_bills_account_orderitem
            $yc_fee = 0.00;
            foreach ($orderlist as $k2 =>$item) {
                //检查是否有退款
                $item = $this->refund_d($item);
                if($item === 1){
                    continue;
                }
                $orderinsert[] = [
                    'account_id' => $account_id,
                    'order_id' => $item['order_id'],
                    'name' => $item['name'],
                    'yc_rate' => $item['qgs_rate'],
                    'yc_fee' => $item['qgs_fee'],
                    'cost_freight' => $item['cost_freight'],
                    'order_price' => $item['cost_item'],
                    'off_price' => bcsub($item['g_price'], $item['price'], 2),
                    'pay_price' => $item['total_amount'],
                    'createtime' => $item['last_modified'],
                    'paymethod_id' => $item['paymethod_id'],
                    'bandle_fee' => 0,
                    'ship_name' => $item['ship_name'],
                    'nickname' => $item['nickname'],
                ];
                $yc_fee += $item['qgs_fee'];
            }
            //dump($orderinsert);die;
            $res1 = M('b2c_bills_account_orderitem')->addAll($orderinsert);
            if ($res1 === false) {
                $db->rollback();
                $this->error('新增出错order');
            }
        }
        //修改订单数据：把未结算改为结算
        $o_stat = M('b2c_orders')->where(['order_id' => ['in', $orderids]])->save(['js_type' => 2]);
        if ($o_stat === false) {
            $db->rollback();
            $this->error('修改订单数据');
        }
        $account = [
            'account_id' => $account_id,
            'local_id' => $local_id,
            'local_name' => $local_name,
            'create_time' => time(),
            'start_time' => $start_time,
            'end_time' => $end_time,
            'money' => bcsub($orderZ['final_price'], $refundZ['final_price'], 2),
            'handle_id' => session('userInfo')['local_id'],
            'handle_name' => session('userInfo')['username'],
            'is_ticket' => '0', //默认不开票
            'remark' => $handle_tips,
            'order_num' => $orderZ['nums'],
            'order_totalPrice' => $orderZ['origin_price'],
            'order_commission' => $yc_fee,
            'order_bank' => $orderZ['bank'],
            'order_other' => $orderZ['other'],
            'order_youhui' => $orderZ['total_off'],
            'order_yongjin' => $orderZ['total_yongjin'],
            'order_finalPirce' => $orderZ['final_price'],
            'refund_num' => $refundZ['nums'],
            'refund_commission' => $refundZ['total_yongjin'] ? $refundZ['total_yongjin'] : '0.00',
            'refund_other' => $refundZ['other'],
            'refund_totalPrice' => $refundZ['origin_price'] ? $refundZ['origin_price'] : '0.00',
            'refund_finalPrice' => $refundZ['final_price'] ? $refundZ['final_price'] : '0.00',
            'final_accountMoney' => $yc_fee - $orderZ['other'] - $orderZ['bank'],
            'qgs_reality_money' => $yc_fee - $orderZ['other'] - $orderZ['bank'],
            // 'final_accountMoney' => $orderZ['final_price'],
            'is_terrace' => 2,
        ];
        $res = M('b2c_bills_account')->add($account);
        //echo M('b2c_bills_account')->getLastSql();exit;
        //var_dump($res);
        if (!$res) {
            $db->rollback();
            $this->error('新增出错');
        }

        $db->commit();
        redirect(U('index'));
    }

    /**
     * 判断订单是否有退款
     * 1-这个订单号的单个商品劝退，0-该订单该商品无退款，其他-真实佣金
     */
    public function refund_d($item){
        //查询是否退款
        $refundSql = "SELECT rg.*,rm.price FROM `sdb_b2c_refund_money_goods` rg INNER JOIN `sdb_b2c_refund_money` rm ON rg.refund_money_id = rm.id WHERE rm.`status` = '5' and rg.order_id = {$item['order_id']}";
        $refundData = M()->query($refundSql);
        foreach($refundData as $k1 => $v1){
            if($item['item_id'] == $v1['item_id']){
                if($item['nums'] == $v1['num']){
                    return 1;
                }else{
                    //真实佣金 = 下单佣金减去退款的佣金
                    $item['qgs_fee'] = round(bcsub($item['qgs_fee'] , ($v1['price'] * $item['qgs_fee']/100),3),2);
                }
            }
        }
        return $item;
    }

    /**
     * 编辑对账单
     */
    public function edit()
    {
        $id = I('get.id', '', 'intval');
        if (!$id) $this->error('id缺失');
        //汇总信息
        $info = M('b2c_bills_account')->where(['id' => $id])->find();
        //dump($info);
        $this->assign('info', $info);
        //入账信息
        $order_list = M('b2c_bills_account_orderitem')->where(['account_id' => $info['account_id']])->select();
        //dump($order_list);
        //退款信息
        //$refund_list = M('b2c_bills_account_refunditem')->where(['account_id' => $info['account_id']])->select();
        $payments = M('b2c_payment')->getField('name', true);
        if ($order_list) {
            $order = [];
            $tmp = [];
            /**
             * CREATE TABLE `sdb_b2c_bills_account_orderitem` (
             * `item_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '结算单详情主键id',
             * `account_id` bigint(15) NOT NULL DEFAULT '0' COMMENT '结算单id',
             * `order_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '订单id',
             * `name` varchar(100) NOT NULL DEFAULT '' COMMENT '商品名称',
             * `yc_rate` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '佣金率',
             * `yc_fee` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '抽佣金额',
             * `cost_freight` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '物流费用',
             * `order_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '订单金额',
             * `off_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '门店优惠',
             * `pay_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '实际支付',
             * `createtime` int(10) NOT NULL DEFAULT '0' COMMENT '支付日期',
             * `paymethod_id` tinyint(1) NOT NULL DEFAULT '0' COMMENT '支付方式',
             * `bandle_fee` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '线上手续费',
             * PRIMARY KEY (`item_id`)
             * ) ENGINE=InnoDB AUTO_INCREMENT=74 DEFAULT CHARSET=utf8;
             */
            //订单号 商品 佣金率 抽佣金额 物流费用 订单金额 门店优惠 实支付金额 支付日期 支付方式 线上手续费
            foreach ($order_list as $item) {
                $order[$item['order_id']]['order_id'] = $item['order_id'];//订单id
                $order[$item['order_id']]['total_amount'] = $item['pay_price'];//实际支付价格
                $order[$item['order_id']]['cost_freight'] = $item['cost_freight'];//物流费用
                $order[$item['order_id']]['cost_item'] = $item['order_price'];//订单价格
                $order[$item['order_id']]['createtime'] = $item['createtime'];//支付日期
                $order[$item['order_id']]['paymethod_id'] = $item['paymethod_id'];//支付方式
                $order[$item['order_id']]['nickname'] = $item['nickname'];//会员昵称
                $order[$item['order_id']]['ship_name'] = $item['ship_name'];//收货人
                if ($item['paymethod_id']) {
                    $order[$item['order_id']]['paymethod_name'] = $payments[$item['paymethod_id'] - 1];//支付方式
                } else {
                    $order[$item['order_id']]['paymethod_name'] = '';
                }
                $order[$item['order_id']]['list'] = [];
                $ii = [
                    'name' => $item['name'],//货品名称
                    //'nums' => $item['nums'],//数量
                    'yc_rate' => $item['yc_rate'],
                    'yc_fee' => $item['yc_fee'],
                    'youhui' => $item['off_price'],
                ];
                $tmp[$item['order_id']][] = $ii;
                $order[$item['order_id']]['list'] = $tmp[$item['order_id']];
                $order[$item['order_id']]['geshu'] = count($order[$item['order_id']]['list']);
                $order[$item['order_id']]['yongjin'] = array_sum(array_column($tmp[$item['order_id']], 'yc_fee'));
            }
            sort($order);
            $this->assign('order', $order);
        }
        /*if ($refund_list) {
            $refund = [];
            $tmp = [];

             // `sdb_b2c_bills_account_refunditem`
            //订单号 商品 佣金率 抽佣金额 退款金额  退款完成日期 门店经办 退款经办
            foreach ($refund_list as $item) {
                //序 订单号  商品  佣金率  抽佣金额  退款金额  退款完成日期 门店经办  退款经办  操作
                $refund[$item['order_id']]['order_id'] = $item['order_id'];//订单id
                $refund[$item['order_id']]['price_detail'] = $item['price_detail'];//退款金额
                $refund[$item['order_id']]['finance_confirm_t'] = $item['createtime'];//退款完成日期
                $refund[$item['order_id']]['finance_name'] = $item['finance_user'];//退款经办
                $refund[$item['order_id']]['store_name'] = $item['store_user'];
                $refund[$item['order_id']]['list'] = [];
                $ii = [
                    'name' => $item['name'],//货品名称
                    //'nums' => $item['nums'],//数量
                    'yc_rate' => $item['yc_rate'],
                    'yc_fee' => $item['yc_fee'],
                ];
                $tmp[$item['order_id']][] = $ii;
                $refund[$item['order_id']]['list'] = $tmp[$item['order_id']];
                $refund[$item['order_id']]['geshu'] = count($refund[$item['order_id']]['list']);
                $refund[$item['order_id']]['yongjin'] = array_sum(array_column($tmp[$item['order_id']], 'yc_fee'));
            }
            sort($refund);
            $this->assign('refund', $refund);
        }*/

        $this->display();
    }

    /**
     * 保存修改
     */
    public function saveEdit()
    {
        $id = I('post.id', 0, 'intval');
        $orderids = I('post.order', []);
        $bank = I('post.bank');
        $other = I('post.other');
        $refundids = I('post.refund', []);
        $other2 = I('post.other2');
        $handle_name = session('userInfo')['username'];
        $handle_tips = I('post.handle_tips', '');
        if (!$id) $this->error();
        $info = M('b2c_bills_account')->where(['id' => $id])->find();

        //重建order总结数据
        $orderres = $this->rebuildOrders($orderids, $bank, $other);
        $orderlist = $orderres['orderlist'];
        $orderZ = $orderres['orderZ'];
        $db = new Model();
        $db->startTrans();
        //清空掉以前的老数据(入账信息)

        $beforeAll = M('b2c_bills_account_orderitem')->where(['account_id' => $info['account_id']])->field('item_id,order_id')->select();

        if ($beforeAll) {
            $tmp = [];
            foreach ($beforeAll as $item) {
                if (!in_array($item['order_id'], $orderids)) {
                    array_push($tmp, $item['item_id']);
                }
            }

            if ($tmp) {
                //删除多余的item
                $delres = M('b2c_bills_account_orderitem')->where(['item_id' => ['in', $tmp]])->delete();
                if ($delres === false) {
                    $db->rollback();
                    $this->error('删除老订单数据失败');
                }
            }
        }
        $yc_fee = 0.00;
        foreach ($orderlist as $k2 =>$item) {
            //检查是否有退款
            $item = $this->refund_d($item);
            if($item === 1){
                continue;
            }
            $yc_fee += $item['qgs_fee'];
        }
        if($yc_fee){
            $orderZ['total_yongjin'] = $yc_fee;
        }

        //更新account表数据
        $account = [
            'create_time' => time(),
            'money' => $orderZ['final_price'],

            'handle_id' => session('userInfo')['local_id'],
            'handle_name' => session('userInfo')['username'],
            'is_ticket' => '0', //默认不开票
            'remark' => $handle_tips,
            'order_num' => $orderZ['nums'],
            'order_totalPrice' => $orderZ['origin_price'],
            'order_commission' => $orderZ['total_yongjin'],
            'order_bank' => $orderZ['bank'],
            'order_other' => $orderZ['other'],
            'order_finalPirce' => $orderZ['final_price'],
            //'refund_num' => $refundZ['nums'],
            //'refund_commission' => $refundZ['total_yongjin'],
            //'refund_other' => $refundZ['other'],
            //'refund_totalPrice' => $refundZ['origin_price'],
            //'refund_finalPrice' => $refundZ['final_price'],
            'final_accountMoney' => $orderZ['total_yongjin'] - $orderZ['other'] - $orderZ['bank'],
            'qgs_reality_money' => $orderZ['total_yongjin'] - $orderZ['other'] - $orderZ['bank'],
            //'final_accountMoney' => $orderZ['final_price'],
        ];

        $account_res = M('b2c_bills_account')->where(['id' => $id])->save($account);
        if ($account_res === false) {
            $db->rollback();
            $this->error('更新主表信息失败');
        }
        //全部保存成功之后跳转到首页
        $db->commit();
        redirect(U('index'));
    }

    /**
     * 生成结算单号
     * 格式15 1+日期+rand3+rand3
     */
    public function buildNubmer()
    {
        //var_dump(session('userInfo'));
        $sign = '1' . date("Ymd");

        while (true) {
            list($usec, $sec) = explode(" ", microtime());
            $microtime = (float)$usec + (float)$sec;
            mt_srand($microtime);
            $randval = substr(mt_rand(), 2, 3) . rand(100, 999);
            $strList = $sign . $randval;
            $aRet = M('b2c_bills_account')->where(['account_id' => $strList])->count();
            if (!$aRet) {
                break;
            }
        }
        return $sign . $randval;
    }

    public function doneyiyi()
    {
        $id = I('post.id');
        if (!IS_AJAX || !$id) {
            $this->ajaxReturn(['status' => false, 'message' => '非法请求', 'data' => []]);
        }
        $res = M('b2c_bills_account')->where(['id' => $id])->save(['state' => '1']);
        if ($res !== false) {
            $this->ajaxReturn(['status' => true, 'message' => '成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'message' => '失败了', 'data' => []]);
        }
    }

    /**
     * 查看结算单
     */
    public function view()
    {

        $id = $id ? $id : I('get.id', '', 'intval');
        if (!$id) $this->error('id缺失');
        $bill_model = new BillsExportModel();
        $bill_model->id = $id;
        $res = $bill_model->view();
        $this->assign($res);
        $this->display('view');
    }

    public function uploadimg()
    {
        $id = I('post.id');
        $img = I('post.img');
        if (!IS_AJAX || !$id) {
            $this->ajaxReturn(['status' => false, 'message' => '非法请求', 'data' => []]);
        }
        $res = M('b2c_bills_account')->where(['id' => $id])->save(['money_img' => $img, 'update_time' => time()]);
        if ($res !== false) {
            $this->ajaxReturn(['status' => true, 'message' => '成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'message' => '失败了', 'data' => []]);
        }
    }

    /**
     * 提出异议 改变状态 异议留言
     */
    public function sendyiyi()
    {
        $id = I('post.id');
        if (!IS_AJAX || !$id) {
            $this->ajaxReturn(['status' => false, 'message' => '非法请求', 'data' => []]);
        }
        $name = I('post.name');
        $tel = I('post.tel');
        $desc = I('post.desc');
        $exists = M('b2c_bills_account')->where(['id' => $id])->getField('talk');
        if ($exists) {
            $talk = json_decode($exists, true);
            array_push($talk, [
                'name' => $name,
                'tel' => $tel,
                'desc' => $desc,
                'time' => time(),
                'role' => 'pingtai',
            ]);
        } else {

            $talk[0] = [
                'name' => $name,
                'tel' => $tel,
                'desc' => $desc,
                'time' => time(),
                'role' => 'store',
            ];
        }
        $res = M('b2c_bills_account')->where(['id' => $id])->save(['state' => '2', 'talk' => json_encode($talk)]);
        if ($res !== false) {
            $this->ajaxReturn(['status' => true, 'message' => '成功', 'data' => []]);
        } else {
            $this->ajaxReturn(['status' => false, 'message' => '修改失败', 'data' => []]);
        }
    }

    /**
     * 导出结算单
     */
    public function exportExcel()
    {
        $id = I('get.id');
        if (!$id) $this->error('id缺失');

        $exp = new BillsExportModel();
        $exp->id = $id;
        $exp->exportExcel();
    }

    /**
     * 删除结算单列表
     */
    public function delete()
    {
        $id = I('get.id', '', 'intval');
        if (!$id) $this->error('id缺失');

        $b2c_bills_account = M('b2c_bills_account');
        // 结算单列表
        $info = $b2c_bills_account->where(['id' => $id])->find();
        if (empty($info) || $info['type'] == '1') {
            $this->error('没有这个结算单');
        }

        try {
            M()->execute('begin');

            $d1 = $b2c_bills_account->where(['id' => $id])->delete();
            if ($d1 === 0) {
                throw new \Exception(false);
            }

            $bills_account_orderitem = M('b2c_bills_account_orderitem')->where(['account_id' => $info['account_id']])->select();
            if ($bills_account_orderitem) {
                $d2 = M('b2c_bills_account_orderitem')->where(['account_id' => $info['account_id']])->delete();
                if ($d2 === 0) {
                    throw new \Exception(false);
                }
            }
            $bills_account_refunditem = M('b2c_bills_account_refunditem')->where(['account_id' => $info['account_id']])->select();
            if ($bills_account_refunditem) {
                $d3 = M('b2c_bills_account_refunditem')->where(['account_id' => $info['account_id']])->delete();
                if ($d3 === 0) {
                    throw new \Exception(false);
                }
            }
            M()->execute('commit');
            $this->success('删除成功', U('index'));
        } catch (\Exception $e) {
            M()->execute('rollback');
            $this->error('删除失败');
        }

    }
}